package com.code.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: JWT工具类
 * @Author: Huangds
 * @Date：2020/1/12 23:12
 * @Modified By:
 * @Version: v1.0
 */
public class JWTUtil {
    private static final String TOKEN_SECRET = "Huangds";
    private static final String CLAIM_NAME = "sign";
    private static final long EXPIRE_TIME = 15 * 60 * 1000;

    /**
     * @Description: 获取token
     * @Author: Huangds
     * @Date: 2020/1/12 23:17
     * @Modified By:
     * @Version: v1.0
     */
    public static String sign(String sign) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET); // 加密的签名
            Map<String, Object> header = new HashMap<>(); // 加密头
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); // 超时时间
            String token = JWT.create().withHeader(header).withClaim(CLAIM_NAME, sign).withExpiresAt(date).sign(algorithm); // 令牌token
            return token;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @Description: 校验token
     * @Author: Huangds
     * @Date: 2020/1/12 23:17
     * @Modified By:
     * @Version: v1.0
     */
    public static String verify(String token) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaim(CLAIM_NAME).asString();
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
        //System.out.println(JWTUtil.sign("缠中说禅"));
//        System.out.println(JWTUtil.verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzaWduIjoi57yg5Lit6K-056aFIiwiZXhwIjoxNTc4ODQzMjMzfQ.uAQh4f0mu9GfIlSxqSUDiNXWSXJZwB7XVI5zEqpVIjE"));
    }

}
